﻿using DataProcess.Interface;
using DataProcess.Interface.Models;
using System;
using System.Linq;
using System.Text.RegularExpressions;

namespace DataProcessing.OXFORD
{
    public class DataProcessing : IDataProcessing
    {
        public string Name { get { return "OXFORD(牛津) 荧光仪"; } }

        public IDataOutput Processing(string content)
        {
            XRayOutputModel outputModel = new XRayOutputModel();
            var regContext = new Regex("[\r\n]+").Replace(content, "\r");
            string[] spdata = regContext.Split('\r');
            for (int i = 0; i <= spdata.Length - 1; i++)
            {
                switch (i)
                {
                    case 0:
                        var sample = Regex.Match(spdata[i], @"(?<=Sample:,)([\w\W]*)");
                        if (sample.Success)
                        {
                            outputModel.SampleName = sample.Value.Replace(',', ' ');
                        }
                        break;
                    case 1:
                        var dateMatch = Regex.Match(spdata[i], @"(?<=,)([\w\W]*)(?=,at,)");
                        var timeMatch = Regex.Match(spdata[i], @"(?<=,at,)([\w\W]*)");

                        string dateStr = $"{dateMatch} {timeMatch}";

                        if (DateTime.TryParseExact(dateStr, "dd/MM/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out DateTime date))
                        {
                            outputModel.MeasureTime = date;
                        }
                        else
                        {
                            outputModel.MeasureTime = DateTime.Now;
                        }
                        break;
                    case 2:
                        var method = Regex.Match(spdata[i], @"(?<=Method,Name:,)([\w\W]*)");
                        if (method.Success) outputModel.AnalyzeApplicationName = method.Value;
                        break;
                    default:
                        int defo = spdata[i].IndexOf(",");
                        if (defo > -1)
                        {
                            var reItem = new Regex("[\\s,]+").Replace(spdata[i], ",");
                            string[] spItem = reItem.Split(',').Select(it => it.TrimEnd().TrimStart()).Where(it => !string.IsNullOrEmpty(it)).ToArray();

                            if (!outputModel.Eelements.ContainsKey(spItem[0]))
                            {
                                if (double.TryParse(spItem[1], out _)) outputModel.Eelements.Add(spItem[0], spItem[1]);
                            }
                        }
                        break;
                }
            }
            return outputModel;
        }
    }
}
